package models

import (
	"errors"
	"fmt"
	"git.inedcn.com/ined/cmn"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type MerchantModel struct {
	Id        int64        `xorm:"pk autoincr" json:"id"`
	CreatedAt cmn.JsonTime `xorm:"created" json:"created_at"`
	UpdatedAt cmn.JsonTime `xorm:"updated" json:"updated_at"`
	DeletedAt cmn.JsonTime `xorm:"deleted" json:"-"`
	Name      string       `json:"name"`
	Cellphone string       `json:"cellphone"`
	Phone     string       `json:"phone"`
	Tags      []string     `json:"tags"`
	Address   string       `json:"address"`
	Lat       string       `json:"lat"`
	Lon       string       `json:"lon"`
}

type MerchantQuery struct {
	Limit  int    `json:"limit"`
	Offset int    `json:"offset"`
	Name   string `json:"name"`
}

func (pm *MerchantModel) TableName() string {
	return "merchant"
}

func (u *MerchantModel) Query(query MerchantQuery) ([]User, int64, error) {
	users := make([]User, 0)
	s := app.DB().Table("merchant")

	if query.Name != "" {
		s.Where("name=?", query.Name)
	}

	total, err := s.Limit(query.Limit, query.Offset).OrderBy("id desc").FindAndCount(&users)
	if err != nil {
		middlewares.Logger.Println("ERROR - User Query failed ", err)
		return nil, 0, errors.New("获取商户列表失败")
	}

	return users, total, nil
}

func (u *MerchantModel) Create() (*MerchantModel, error) {
	_, err := app.DB().Insert(u)
	if err != nil {
		middlewares.Logger.Println("insert user fail", err)
		return nil, err
	}
	mm := &MerchantModel{}
	_, err = app.DB().Where("cellphone=?", u.Cellphone).Get(mm)
	return mm, err
}

func (u *MerchantModel) Update() (*MerchantModel, error) {
	_, err := app.DB().ID(u.Id).Cols("cellphone", "name", "address").Update(u)
	if err != nil {
		middlewares.Logger.Println("update user fail", err)
		return nil, err
	}
	fmt.Println(u.CreatedAt)
	return u, err
}

func (um *MerchantModel) FindById(id int64) (*MerchantModel, bool, error) {
	u := &MerchantModel{}
	has, err := app.DB().ID(id).Get(u)
	if err != nil {
		middlewares.Logger.Println("find by id doctor", err)
		return nil, false, err
	}
	return u, has, err
}
